package com.xsz.controller;

import com.xsz.entity.User;
import com.xsz.service.UserService;
import com.xsz.util.MD5Utils;
import com.xsz.util.ResultVOUtil;
import com.xsz.vo.ResultVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/login")
    public ResultVO selectByNamePwd(@RequestBody User user) {
        String password=user.getPwd();
        String username=user.getName();
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return ResultVOUtil.success();
        } catch (UnknownAccountException e) {
            return ResultVOUtil.error(500,e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return ResultVOUtil.error(500,e.getMessage());
        } catch (LockedAccountException e) {
            return ResultVOUtil.error(500,e.getMessage());
        } catch (AuthenticationException e) {
            return ResultVOUtil.error(500,"登录失败");
        }
    }

    @PostMapping("/register")
    public ResultVO add(@RequestBody  User user) {
        String password = MD5Utils.encrypt(user.getName(), user.getPwd());
        user.setPwd(password);
        return ResultVOUtil.success(userService.add(user));
    }
}
